package ldh.im.admin.controller;

import ldh.im.admin.pojo.Authority;
import ldh.im.admin.pojo.Role;
import ldh.im.admin.pojo.User;
import ldh.im.admin.pojo.where.AuthorityWhere;
import ldh.im.admin.service.AuthorityService;
import ldh.im.admin.service.RoleService;
import ldh.im.admin.service.UserService;
import ldh.im.admin.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private AuthorityService authorityService;

//    @PreAuthorize("hasRole('admin')")
    @RequestMapping(method = RequestMethod.GET, value = "/initAuthority")
    @ResponseBody
    public String save(Model model, HttpSession httpSession) throws Exception {
        User user = UserUtil.getLoginUser(httpSession);
        Objects.requireNonNull(user);
        Role role = roleService.getManyAuthoritysById(1L);

        User dbUser = userService.getManyRolesById(user.getId());
        boolean isHaveOauthRole = dbUser.getRoles().stream().filter(role1->role1.getId().equals(role.getId())).findAny().isPresent();
        if (!isHaveOauthRole) {
            userService.userAuthorize(dbUser, new ArrayList<>(), Arrays.asList(role));
        }

        if (role.getAuthoritys().size() != 0) return "";
        AuthorityWhere authorityWhere = new AuthorityWhere();
        List<Authority> authorityList = authorityService.getAllAuthoritys(authorityWhere);
        roleService.roleAuthorize(role, new ArrayList<>(), authorityList);
        return "success";
    }
}
